package com.liao.badminton.handler;


import com.alibaba.fastjson.JSON;
import com.liao.badminton.dto.SystemUsersDto;
import com.liao.badminton.code.util.NettyUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.log4j.Log4j2;


@Log4j2
public class NettyServerMyselfHandler extends SimpleChannelInboundHandler<SystemUsersDto> {

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("注册--{}", ctx.channel().remoteAddress());
        NettyUtil.addClientCache(ctx);
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.info("注销--{}", ctx.channel().remoteAddress());
        super.channelUnregistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("激活--------------{}", ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("失效--------------{}", ctx.channel().remoteAddress());
        super.channelInactive(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("读取完成--------------");
        super.channelReadComplete(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("事件触发---接连，读，写，超时-----------{}", JSON.toJSONString(evt));
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        super.channelWritabilityChanged(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("客户端：{}，异常：{}", ctx.channel().remoteAddress(), cause.getMessage());
        NettyUtil.clear(ctx);
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SystemUsersDto msg) throws Exception {
        log.info("客户端收到消息：{}", JSON.toJSONString(msg));
        msg.setUsername(msg.getUsername() + "_server");
        ctx.writeAndFlush(msg);
    }
}
